Online-Academy
Look, Read, Understand, Apply

Synchronizing Specific Object

Synchronizing on a Specific Object

The join() calls ensure that the main thread waits for both threads to finish before printing the result.

We can use a separate lock object:

class Counter {
    int count = 0;
    private final Object lock = new Object();
    void increment() {
        synchronized (lock) {
            count++;
        }
    }
}
public class SynchroObject_Lock_Demo {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println("Final count: " + counter.count);
    }
}